﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

using Dxr.Police.Models;
using Dxr.Police.Services;
using Dxr.Police.Web.Models;

using Zongsoft.Data;
using Zongsoft.Web.Http;
using Zongsoft.Security.Membership;

namespace Dxr.Police.Web.Http.Controllers
{
    [Authorization(new[] { Dxr.Police.Models.Role.Admin, Dxr.Police.Models.Role.Manager })]
    public class UserController : ControllerBase<UserInfo, UserInfoConditional, UserInfoService>
    {
        public UserController(Zongsoft.Services.IServiceProvider serviceProvider) : base(serviceProvider)
        {
        }

        [Authorization(AuthorizationMode.Anonymous)]
        public override HttpResult Post(UserInfo model)
        {
            model.Id = RequestContext.Principal.Identity.Name;

            if (string.IsNullOrEmpty(model.Id))
                throw HttpResponseExceptionUtility.BadRequest("Missing the id argument.");

            return base.Post(model);
        }

        public override HttpResult Query(UserInfoConditional conditional, [FromUri] Paging paging = null)
        {
            switch (UserInfo.Role)
            {
                case Dxr.Police.Models.RoleType.Manager:
                    if (!string.IsNullOrEmpty(UserInfo.CountyId))
                        conditional.CountyId = UserInfo.CountyId;

                    if (!string.IsNullOrEmpty(UserInfo.DepartmentId))
                        conditional.DepartmentId = UserInfo.DepartmentId;

                    if (!string.IsNullOrEmpty(UserInfo.WorkPlaceId))
                        conditional.WorkPlaceId = UserInfo.WorkPlaceId;
                    break;
            }
            return base.Query(conditional, paging);
        }

        protected override object ToDisplayModel(UserInfo model)
        {
            return model.ToDisplayModel();
        }

        [Authorization(AuthorizationMode.Identity)]
        public HttpResult GetRole()
        {
            return new HttpResult()
            {
                ret = HttpResult.Success,
                content = UserInfo.Role
            };
        }
    }
}
